<?php

namespace App\Admin\Controllers;

use App\Models\Major;
use App\Models\User;
use App\Models\University;
use App\Models\Campus;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\MessageBag;

use Encore\Admin\Widgets\Table;

class UserController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {

        return Admin::content(function (Content $content) {

            $content->header('会员列表');
            $content->description('显示所有的会员');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('会员列表');
            $content->description('description');

            $content->body($this->form($action='edit')->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('会员列表');
            $content->description('description');
            $content->body($this->form($action='create'));
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        Admin::script($this->script());
        return Admin::grid(User::class, function (Grid $grid) {
           
            $grid->actions(function ($actions) {
                // prepend一个操作
                $actions->disableDelete();
                $actions->prepend('<a href="'.url('admin/users?spread_uid='.$actions->getKey()).'">推广校友</a>&#12288;');

                $actions->prepend('<a href="'.url('admin/depot?user_id='.$actions->getKey()).'">书店</a>&#12288;');
            });
            $spread_uid=request()->spread_uid;
            if($spread_uid){
                $grid->model()->where('spread_uid', $spread_uid);
            }
            $grid->id('ID')->sortable();
            $grid->head_img('头像')->display(function ($data) {
                if (!$data) {
                    return '';
                }
                return <<<DATA
<img src="{$data}" 
style="width:50px;height:50px;border-radius: 50%;" class="img">
DATA;
            });

            $grid->nickname('昵称')->display(function ($data){
                return deal_emoji($data);
            });
            $grid->gender('性别')->display(function($gender){
                $text='保密';
                if($gender==1){
                    $text='男';
                }elseif ($gender==2){
                    $text='女';
                }
                return $text;
            });
            $grid->phone_number('联系方式');
            $grid->university_id('大学')->display(function ($data){
                return University::where('id',$data)->value('name')?:'';

            });
            $grid->balance('余额');
            $grid->subscribe('当前关注状态')->display(function($data){
                return $data?'已关注':'';
            });
            $grid->spread_uid('推荐大使id');

            $grid->spread_status('用户类型')->display(function($data){
               return $data?'校园推广大使':'普通用户';
            });


            $grid->more('更多')->display(function(){
                $campus=Campus::where('id',$this->campus_id)->value('name')?:'';
                $manager=$this->manager?'是':'';
                $rows = [
                    ['openid', $this->openid],
                    ['关注时间',date('Y-m-d H:i:s',$this->subscribe_time)],
                    ['创建时间',$this->created_at],
                    ['更新时间',$this->updated_at],
                    ['国籍',$this->province],
                    ['省份',$this->province],
                    ['城市',$this->city],
                    ['校区', $campus],
                    ['地址',$this->address],
                    ['管理员',$manager],
                    ['分享码',$this->share_code],
                    ['推荐大使id',$this->spread_uid],
                    ['推广二维码',$this->spread_qrcode],
                    ['微信备注',$this->remark],
                ];
                $table = new Table([], $rows);
                return <<<DATA
<a class="btn btn-xs btn-default grid-expand" data-inserted="0" data-key="{$this->id}" 
data-toggle="collapse" data-target="#grid-collapse-{$this->id}">
    <i class="fa fa-caret-right"></i> 详情
</a>
<template class="grid-expand-{$this->id}">
    <div id="grid-collapse-{$this->id}" class="collapse">
   {$table}
</div>
</template>
DATA;
            });
            $grid->filter(function($filter){
                // 在这里添加字段过滤器
                $filter->like('phone_number', '注册号码');

            });


        });
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(User::class, function (Form $form)  {

            $form->number('balance','余额');
            $states = [
                'on'  => ['value' => 1, 'text' => '打开', 'color' => 'success'],
                'off' => ['value' => 0, 'text' => '关闭', 'color' => 'danger'],
            ];

            $form->switch('spread_status','校园推广大使')->states($states);
            $form->radio('manager','微信业务处理员')->options(['1'=> '是','0' => '不是' ])->default('0');
            $form->saving(function (Form $form) {
                if(!$form->model()->spread_qrcode && $form->spread_status=='on'){
                    //需要生成推广二维码
                    $qrcode=app('wechat')->qrcode;
                    $result = $qrcode->forever($form->model()->id);
                    $ticket = $result->ticket;
                    $url = $qrcode->url($ticket);
                    if(!$url){
                        $error = new MessageBag([
                            'title'   => '错误提示',
                            'message' => '生成推广二维码失败',
                        ]);
                        return back()->with(compact('error'));
                    }
                    $form->model()->spread_qrcode=$url;
                }
            });
        });
    }

    protected function script()
    {
        return <<<SCRIPT
$('.grid-expand').on('click', function () {
     if ($(this).data('inserted') == '0') {
        var key = $(this).data('key');
        var row = $(this).closest('tr');
        var html = $('template.grid-expand-'+key).html();

        row.after("<tr><td colspan='"+row.find('td').length+"' style='padding:0 !important; border:0px;'>"+html+"</td></tr>");

        $(this).data('inserted', 1);
    }

    $("i", this).toggleClass("fa-caret-right fa-caret-down");

});

SCRIPT;
    }

}
